package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.PaymentOrder;
import com.smartcampusbackend.model.CampusCardBalance;
import com.smartcampusbackend.service.PaymentOrderService;
import com.smartcampusbackend.service.CampusCardBalanceService;
import com.smartcampusbackend.service.SchoolAccountService;
import com.smartcampusbackend.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/payment")
public class PaymentController {
    @Autowired
    private PaymentOrderService paymentOrderService;
    @Autowired
    private CampusCardBalanceService campusCardBalanceService;
    @Autowired
    private SchoolAccountService schoolAccountService;
    @Autowired
    private AlipayService alipayService;

    // 创建订单
    @PostMapping("/order")
    public ResponseEntity<?> createOrder(@RequestBody PaymentOrder order) {
        // 验证学生专业信息（仅学费和住宿费需要验证）
        if (("tuition".equals(order.getCategory()) || "accommodation".equals(order.getCategory())) 
            && !paymentOrderService.validateStudentMajor(order.getUserId())) {
            return ResponseEntity.badRequest().body(Map.of("message", "学生专业信息不完整，无法创建缴费订单"));
        }
        
        PaymentOrder result = paymentOrderService.createOrder(order);
        return ResponseEntity.ok(result);
    }

    // 支付订单（支持模拟支付和支付宝支付）
    @PostMapping("/pay")
    public ResponseEntity<?> payOrder(@RequestParam String orderNo, @RequestParam String payMethod) {
        // 如果是支付宝支付，返回二维码信息
        if ("alipay".equals(payMethod)) {
            PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", "订单不存在"));
            }
            
            // 调用支付宝服务生成支付二维码
            String subject = generateSubject(order.getCategory(), order.getYear());
            Map<String, Object> alipayResult = alipayService.createPayment(
                order.getOrderNo(),
                subject,
                order.getAmount().toString()
            );
            
            if ((Boolean) alipayResult.get("success")) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("payMethod", "alipay");
                result.put("qrCode", alipayResult.get("qrCode"));
                result.put("outTradeNo", alipayResult.get("outTradeNo"));
                result.put("subject", alipayResult.get("subject"));
                result.put("amount", order.getAmount());
                result.put("message", alipayResult.get("message"));
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(Map.of("success", false, "message", alipayResult.get("message")));
            }
        } else {
            // 模拟支付
            boolean success = paymentOrderService.payOrder(orderNo, payMethod);
            if (success) {
                // 获取订单金额
                PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
                if (order != null && order.getAmount() != null) {
                    schoolAccountService.recharge(order.getAmount());
                }
            }
            return ResponseEntity.ok(Map.of("success", success));
        }
    }

    // 取消订单
    @PostMapping("/cancel")
    public ResponseEntity<?> cancelOrder(@RequestParam String orderNo) {
        boolean success = paymentOrderService.cancelOrder(orderNo);
        return ResponseEntity.ok(Map.of("success", success));
    }

    // 查询历史订单（根据角色权限）
    @GetMapping("/history")
    public ResponseEntity<?> getUserOrders(
            @RequestParam Integer userId, 
            @RequestParam(required = false) String year, 
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String userRole) {
        
        List<PaymentOrder> orders = paymentOrderService.getUserOrders(userId, year, category, userRole);
        return ResponseEntity.ok(orders);
    }

    // 管理员查询所有订单
    @GetMapping("/admin/orders")
    public ResponseEntity<?> getAllOrders(
            @RequestParam(required = false) String year, 
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String username) {
        
        List<PaymentOrder> orders = paymentOrderService.getAllOrders(year, category, username);
        return ResponseEntity.ok(orders);
    }

    // 查询订单详情
    @GetMapping("/order/{orderNo}")
    public ResponseEntity<?> getOrderByOrderNo(@PathVariable String orderNo) {
        PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
        if (order == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(order);
    }

    // 查询校园卡余额
    @GetMapping("/card/balance")
    public ResponseEntity<?> getCardBalance(@RequestParam Integer userId) {
        CampusCardBalance balance = campusCardBalanceService.getBalance(userId);
        if (balance == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("balance", BigDecimal.ZERO);
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.ok(balance);
    }

    // 校园卡充值
    @PostMapping("/card/recharge")
    public ResponseEntity<?> recharge(@RequestParam Integer userId, @RequestParam BigDecimal amount) {
        boolean success = campusCardBalanceService.recharge(userId, amount);
        return ResponseEntity.ok(Map.of("success", success));
    }

    // 获取学生专业费用信息
    @GetMapping("/student/fees")
    public ResponseEntity<?> getStudentFees(@RequestParam Integer userId) {
        Map<String, BigDecimal> fees = paymentOrderService.getStudentFees(userId);
        return ResponseEntity.ok(fees);
    }

    // 验证学生专业信息
    @GetMapping("/student/validate")
    public ResponseEntity<?> validateStudentMajor(@RequestParam Integer userId) {
        boolean isValid = paymentOrderService.validateStudentMajor(userId);
        return ResponseEntity.ok(Map.of("valid", isValid));
    }

    // 查询学校账户余额（管理员可用）
    @GetMapping("/school/account")
    public ResponseEntity<?> getSchoolAccount() {
        return ResponseEntity.ok(schoolAccountService.getAccount());
    }
    
    // 查询支付宝支付状态
    @GetMapping("/alipay/status")
    public ResponseEntity<?> checkAlipayStatus(@RequestParam String orderNo) {
        PaymentOrder order = paymentOrderService.getOrderByOrderNo(orderNo);
        if (order == null) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "订单不存在"));
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("orderNo", order.getOrderNo());
        result.put("status", order.getStatus());
        result.put("payMethod", order.getPayMethod());
        result.put("payTime", order.getPayTime());
        
        return ResponseEntity.ok(result);
    }
    
    // 根据category和year生成支付主题
    private String generateSubject(String category, String year) {
        String yearText = year != null ? year + "年" : "";
        switch (category) {
            case "tuition":
                return "学费缴费" + yearText;
            case "accommodation":
                return "住宿费缴费" + yearText;
            case "card_recharge":
                return "校园卡充值";
            default:
                return "校园缴费" + yearText;
        }
    }
} 